package problems.contest;

import java.util.*;

/**
 * 第 317 场周赛
 * <p>https://leetcode.cn/contest/weekly-contest-317</p>
 *
 * @author habitplus
 * @since 9:26, 2022/10/30
 */
public class WCT317 {
    /**
     * T1|6220. 可被三整除的偶数的平均值
     * <p>https://leetcode.cn/problems/average-value-of-even-numbers-that-are-divisible-by-three/</p>
     */
    public int averageValue(int[] nums) {
        int cnt = 0;
        int sum = 0;
        for (int num : nums) {
            if (num % 2 == 0 && num % 3 == 0) {
                ++cnt;
                sum += num;
            }
        }

        return cnt == 0 ? 0 : sum / cnt;
    }


    /**
     * T2|6221. 最流行的视频创作者
     * <p>https://leetcode.cn/problems/most-popular-video-creator/</p>
     */
    public List<List<String>> mostPopularCreator(String[] creators, String[] ids, int[] views) {
        List<List<String>> ret = new ArrayList<>();

        int n = creators.length;
        long maxP = 0;
        Map<String, long[]> map = new HashMap<>();
        // 防止和溢出
        long[] arr;

        for (int i = 0; i < n; ++i) {
            arr = map.getOrDefault(creators[i], null);
            if (arr == null) {
                arr = new long[] {i, views[i]};
                map.put(creators[i], arr);
            } else {
                if (views[i] > views[(int) arr[0]]) {
                    arr[0] = i;
                } else if (views[i] == views[(int) arr[0]]) {
                    arr[0] = ids[i].compareTo(ids[(int) arr[0]]) < 0 ? i : arr[0];
                }
                arr[1] += views[i];
            }
            maxP = Math.max(maxP, arr[1]);
        }

        for(Map.Entry<String, long[]> e : map.entrySet()) {
            arr = e.getValue();
            if (arr[1] == maxP) {
                List<String> list = Arrays.asList(e.getKey(), ids[(int) arr[0]]);
                ret.add(list);
            }
        }

        return ret;
    }


    /**
     * T3|6222. 美丽整数的最小增量
     * <p>https://leetcode.cn/problems/minimum-addition-to-make-integer-beautiful/</p>
     */
    public long makeIntegerBeautiful(long n, int target) {
        if (n < 1 && target < 1) return 0;

        long origin = n;
        long dig = 1;
        int prevSum;

        while ((prevSum = digitalSum(n)) > target) {

            n += dig;
            // 新的 n 的数位和小于 之前的数位和，
            // 说明当前数位已经是 0，下次相加的加数应该向前进一位
            if (digitalSum(n) < prevSum) dig *= 10;
        }

        return n - origin;

    }

    private int digitalSum(long n) {
        int sum = 0;

        while (n > 0) {
            sum += (int) (n % 10);
            n /= 10;
        }

        return sum;
    }

}
